﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PortScanner
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    public class Config
    {
        // 配置项
        public string Host { get; set; }
        public string Ports { get; set; }
        public int Timeout { get; set; }
        public int ThreadCount { get; set; }

        // AppData 目录下的配置文件路径
        private static string ConfigFilePath =>
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "scanPortConfig.txt");

        // 构造函数，设置默认值
        public Config()
        {
            Host = "localhost";
            Ports = "8080";
            Timeout = 5000; // 默认超时时间为5秒
            ThreadCount = 5; // 默认线程数为5
        }

        // 从文件加载配置
        public static Config LoadConfig()
        {
            if (File.Exists(ConfigFilePath))
            {
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();

                foreach (var line in File.ReadLines(ConfigFilePath))
                {
                    var parts = line.Split(':');
                    if (parts.Length == 2)
                    {
                        var key = parts[0].Trim();
                        var value = parts[1].Trim();
                        keyValuePairs[key] = value;
                    }
                }

                Config config = new Config
                {
                    Host = keyValuePairs.TryGetValue("Host", out var host) ? host : "localhost",
                    Ports = keyValuePairs.TryGetValue("Ports", out var ports) ? ports : "8080",
                    Timeout = keyValuePairs.TryGetValue("Timeout", out var timeout) ?
                              int.TryParse(timeout, out var timeoutVal) ? timeoutVal : 5000 : 5000,
                    ThreadCount = keyValuePairs.TryGetValue("ThreadCount", out var threadCount) ?
                                   int.TryParse(threadCount, out var threadCountVal) ? threadCountVal : 5 : 5
                };

                return config;
            }

            return new Config();
        }

        // 保存配置到文件
        public void SaveConfig()
        {
            string[] lines =
            {
            $"Host: {Host}",
            $"Ports: {Ports}",
            $"Timeout: {Timeout}",
            $"ThreadCount: {ThreadCount}"
        };

            File.WriteAllLines(ConfigFilePath, lines);
        }
    }

}
